from util import *
from os import system
from view import *
import os
# 进度条所需要库
from alive_progress import alive_bar
import time
from time import sleep
from tqdm import tqdm

try:
    name = input('请输入您要下载的小说名：')

    link = get_link(name)  # 获取页面所有链接
    link_name = []

    with tqdm(total=100) as pbar:
        pbar.set_description('全网极力搜索中')
        for u, i in enumerate(link):  # 打印名字
            link_name.append(str(u + 1) + headline(i))
            pbar.update(10)
    while True:
        show_main(link_name)

        name = int(input_1('请输入（按0退出）')) - 1  # 小说选择

        if name == -1:
            exit(0)
        print()
        print('简介：')
        info = ge_info(link[name])
        for i in range(int((len(info) + 1)/2)):
            print(info[i].lstrip())
        n = input('下载/返回（Y/N）:')
        if n in ['Y', 'y']:
            break
        elif n in ['N', 'n']:
            system('cls')
            continue

    file_name = headline(link[name])  # 下载小说名字

    if not os.path.exists('.//小说'):
        system('md 小说')

    md = 'md ' + '.\\小说\\' + file_name
    system(md)  # 创建文件夹

    file = get_section(link[name])  # 所有文件

    items = range(len(file))  # 进度长度
    print('下载中...')
    with alive_bar(len(items)) as bar:  # 进度条显示

        for u, i in enumerate(file):
            path = '.\\' + '小说\\' + file_name + '\\' + str(u + 1) + i[0]
            with open(path, 'w', encoding='utf-8') as f:
                for i in get_text(i[1]):
                    f.writelines(i)
                bar()

except:
    print('')

input('下载完成！')
